package com.mhg.thread;

/**
 * 测试yield方法
 */
public class YeildTest {

    /**
     * 入口程序
     * @param args
     */
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(300L);
                    if (i == 10) {
                        //执行到第20的时候，让出cpu执行权，让cpu重新分配，有可能cpu还是会把执行权分配给本线程
                        Thread.yield();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在执行：" + i);
            }
        }, "thread1");
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(300L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在执行：" + i);
            }
        }, "thread2");

        thread1.start();
        thread2.start();
    }


}
